/**
 * @file time.c
 * time source for TrayInfo.
 */

/* Time support added by Laszlo Ashin <kodest@gmail.com> */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "trayinfo.h"

/** Source handle. */
static source_handle_t *time_sh;

static char *fmt;

static int
time_write(double now, int fd)
{
	char buf[128];
	time_t t;
	struct tm *tmp;
	size_t size;

	t = (time_t)now;
	tmp = localtime(&t);
	if (!tmp) return 0;
	size = strftime(buf, sizeof(buf), fmt ? fmt : "%m-%d %a %H:%M", tmp);
	return show(buf);
}

static int
time_init(source_handle_t *sh)
{
	fmt = NULL;
	return 0;
}

static void
time_done(void)
{
	if (fmt) free(fmt);
	fmt = NULL;
}

static int
time_cfg_fmt(const char *s)
{
	if (fmt) free(fmt);
	fmt = strdup(s);
	return 0;
}

int
init_module(module_phase_t phase)
{
	switch (phase) {
	case MODULE_PHASE_INIT: {
		source_t source = {
			.name = "time",
			.init = time_init,
			.done = time_done,
			.write = time_write,
		};
		time_sh = register_source(&source);
		if (time_sh == NULL) {
			return 0;
		}
		register_config_handler("time-fmt", time_cfg_fmt);
		break;
	}
	case MODULE_PHASE_EXIT:
		forget_config_handler("time-fmt", time_cfg_fmt);
		forget_source(time_sh);
		break;
	}
	return 0;
}
